package com.linln.admin.sync.controller;

import com.linln.admin.app.service.VersionService;
import com.linln.admin.sync.domain.FlowNacos;
import com.linln.admin.sync.service.FlowNacosService;
import com.linln.admin.sync.validator.FlowNacosValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author taofucheng
 * @date 2021/11/26
 */
@Slf4j
@Controller
@RequestMapping("/sync/flownacos")
public class FlowNacosController {

    @Autowired
    private FlowNacosService flowNacosService;
    @Autowired
    private VersionService versionService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("sync:flownacos:index")
    public String index(Model model, FlowNacos flowNacos) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains())
                .withMatcher("data_id", match -> match.contains())
                .withMatcher("add_content", match -> match.contains());


        // 获取数据列表
        Example<FlowNacos> example = Example.of(flowNacos);
        Page<FlowNacos> list = flowNacosService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        model.addAttribute("versions", versionService.getAllDevVersions());
        model.addAttribute("versionId", flowNacos.getVersion_id());
        return "/sync/flownacos/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("sync:flownacos:add")
    public String toAdd(Model model) {
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flownacos/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sync:flownacos:edit")
    public String toEdit(@PathVariable("id") FlowNacos flowNacos, Model model) {
        model.addAttribute("flowNacos", flowNacos);
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flownacos/add";
    }

    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"sync:flownacos:add", "sync:flownacos:edit"})
    @ResponseBody
    @ActionLog(name = "Nacos配置管理", message = "标题：${title}", action = SaveAction.class)
    public ResultVo save(@Validated FlowNacosValid valid, @EntityParam FlowNacos flowNacos) {
        // 复制保留无需修改的数据
        if (flowNacos.getId() != null) {
            FlowNacos beFlowNacos = flowNacosService.getById(flowNacos.getId());
            EntityBeanUtil.copyProperties(beFlowNacos, flowNacos);
        }

        // 保存数据
        flowNacosService.save(flowNacos);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("sync:flownacos:detail")
    public String toDetail(@PathVariable("id") FlowNacos flowNacos, Model model) {
        model.addAttribute("flowNacos", flowNacos);
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flownacos/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("sync:flownacos:status")
    @ResponseBody
    @ActionLog(name = "Nacos配置状态", action = StatusAction.class)
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (flowNacosService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }


    /**
     * 跳转到同步页面
     */
    @GetMapping("/sync")
    @RequiresPermissions("sync:flownacos:sync")
    public String toSync(Model model) {
        return "/sync/flownacos/sync";
    }

    /**
     * 将所有已经上线的配置同步到指定环境中
     *
     * @param combinePubEnv 要同步到哪个环境
     */
    @PostMapping("/sync")
    @RequiresPermissions("sync:flownacos:sync")
    @ResponseBody
    @ActionLog(name = "Nacos配置同步", message = "将所有已上线的nacos配置同步到${combinePubEnv}环境中")
    public ResultVo toSync(String combinePubEnv) {
        if (StringUtils.isBlank(combinePubEnv)) {
            return ResultVoUtil.error("请先选择要同步到哪个环境");
        }

        // 保存数据
        try {
            flowNacosService.sync(combinePubEnv);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultVoUtil.error("同步失败！" + e);
        }
        return ResultVoUtil.success("同步成功！", "同步完成！");
    }
}